<script setup lang="ts">
import { ref, onMounted } from "vue";
import { apiMenuGet, apiMenuPost, apiMenuPut } from "@/tool/request";
import { menu_fileType } from "@/tool/types";
import { GloDragEnd } from "@/tool/tool";
import { showSuccessToast, showToast } from "vant";
import Upload_com from "@/components/upload_com.vue";
import Device from "@/components/device.vue";

const menuItems = ref<menu_fileType[]>([]);
const menu_item = ref<menu_fileType>({
  name: "",
  url: "",
  id: 0,
  foods: [],
  sort: 100,
});
const getData = () => {
  apiMenuGet().then((res) => {
    menuItems.value = res.data.sort(
      (a: menu_fileType, b: menu_fileType) => a.sort - b.sort
    );
  });
};

const handleSortEnd = async (payload: DragEvent, index: number) => {
  const x = payload.x,
    y = payload.y;
  const find_ele = GloDragEnd(x, y, "menu-item");

  // console.log(find_ele, find_ele?.getAttribute("sort"));
  // const sort_index = find_ele?.getAttribute("sort");
  const id_v = find_ele?.getAttribute("id_v");
  if (id_v) {
    // const sort_num = Number(sort_index);
    const id_num = Number(id_v);

    let _find_index = menuItems.value.findIndex((item) => item.id == id_num);
    const _temp = menuItems.value[_find_index];
    if (id_num == _temp.id) {
      return;
    }
    // console.log(_temp.id, _temp.sort, "----",menuItems.value[index].id, menuItems.value[index].sort);
    if (_temp.sort == menuItems.value[index].sort) {
      menuItems.value[index].sort += 1;
      if (_temp.sort == 100) {
        _temp.sort -= 1;
      }
    }

    // sort 交换
    apiMenuPut(_temp.id, { sort: menuItems.value[index].sort }).then((_) => {
      apiMenuPut(menuItems.value[index].id, { sort: _temp.sort }).then((res) => {
        showToast({
          type: "success",
          message: res.data,
        });
        menuItems.value[_find_index] = menuItems.value[index];
        menuItems.value[index] = _temp;
      });
    });

    // apiMenuPut(element.id,{sort:sort_num})
  }
  // try {
  //   const sortedIds = menuItems.value.map((item, index) => ({
  //     id: item.id,
  //     sort: index + 1
  //   }));
  //   await apiMenuGet(sortedIds);
  //   // 更新本地sort值
  //   menuItems.value = menuItems.value.map((item, index) => ({
  //     ...item,
  //     sort: index + 1
  //   }));
  // } catch (error) {
  //   console.error('保存排序失败:', error);
  //   getData(); // 出错时恢复原排序
  // }
};

onMounted(() => {
  getData();
});
const addMenu = (name: string) => {
  apiMenuPost({ name }).then(() => {
    getData();
    menu_item.value.name = "";
  });
};

const success = (url: string) => {
  // console.log(url,menu_item.value);
  if (menu_item.value.id > 0) {
    apiMenuPut(menu_item.value.id, { url: url }).then((res) => {
      showSuccessToast({ message: res.data });
    });
  }
};

</script>

<template>
  <div class="menu-management">
    <van-field v-model="menu_item.name" label="菜品品类" placeholder="请输入菜单品类">
      <template #button>
        <van-button type="primary" @click="addMenu(menu_item.name)" size="mini"
          >添加</van-button
        >
      </template>
    </van-field>

    <Upload_com
      v-if="menu_item.id > 0"
      :url="menu_item.url"
      @success="success"
      style="margin-top: 10px"
    />

    <div class="menu-list">
      <div
        class="menu-item"
        v-for="(element, index) in menuItems"
        :draggable="true"
        v-on:dragend="(event) => handleSortEnd(event, index)"
        :sort="element.sort"
        :id_v="element.id"
        @click="menu_item = element"
        :class="{ active: menu_item.id === element.id }"
      >
        <span class="drag-handle">☰</span>
        {{ element.name }}
      </div>
    </div>
    <van-divider />
    <Device  :file_id="menu_item.id"   v-if="menu_item.id > 0" />
  </div>
</template>

<style scoped lang="scss">
.menu-management {
  .active {
    background: #1989fa !important;
    color: #fff;
  }
  .menu-list {
    display: grid;
    gap: 10px;
    grid-template-columns: repeat(auto-fit, minmax(110px, 1fr));
    text-align: center;
    margin-top: 10px;
  }
  padding: 10px;

  .menu-item {
    display: flex;
    align-items: center;
    gap: 8px;
    background: #fff;
    padding: 8px 12px;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .drag-handle {
      cursor: move;
      user-select: none;
    }
  }
}
// .menu-management {
//   padding: 20px;
// }

// .header {
//   display: flex;
//   justify-content: space-between;
//   align-items: center;
//   margin-bottom: 20px;
// }

// .menu-list {
//   display: grid;
//   gap: 15px;
// }

// .menu-item {
//   display: flex;
//   justify-content: space-between;
//   align-items: center;
//   padding: 15px;
//   background-color: #fff;
//   border-radius: 8px;
//   box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
// }

// .item-info {
//   flex: 1;
// }

// .item-info h3 {
//   margin: 0 0 5px 0;
//   font-size: 16px;
// }

// .item-info p {
//   margin: 3px 0;
//   font-size: 14px;
//   color: #666;
// }

// .item-actions {
//   display: flex;
//   gap: 10px;
// }
</style>
